<?php

/*
 * 这不是一个开放软件，您不能用于商业应用
 * 不允许对程序代码以任何形式任何目的的再发布。
 * Copyright (c) 2015 YOUM.Co.Ltd. All rights reserved..
 * 网站地址：http://www.huishuojs.com
 * Author Zhyu
 */

/**
 * @author Zhyu
 * @date 2015-12-28 01:14:23
 * @copyright 杭州晖硕有码科技
 */
class Cash extends PC_Controller{
    protected $go_url = '/admin/cash/index';
    //put your code here
    public function __construct() {
        parent::__construct();
        $this->load->model('cash_model');
    }
    /**
     * 取现列表
     */
    public function index(){
    	
            $this->data['username'] =  isset($_POST['username'])? $_POST['username'] : '';
            $this->data['select_type']=  isset($_POST['select_type'])?$_POST['select_type']:'or';
            $this->data['start_time']= isset($_POST['start_time'])?$_POST['start_time']:'';
            $this->data['end_time']= isset($_POST['end_time'])?$_POST['end_time']:'';
            $message=$this->uri->segment(4)?$this->uri->segment(4):'1';
            $this->data['message']=$message;
            $this->data['error']    =  empty($_GET['message'])?'':$_GET['message'];
            $this->data['shenhe_all']=$this->Isallow('cash','shenhe_page');
            $this->load->view('/admin/cash_index.php',$this->data);
    }
    /**
     * ajax 获取数据
     */
    public function ajax_cash_list(){
        $user=array();
        $this->load->model('user_model');
        if(isset($_GET['username']) && $_GET['username']){
            $user=$this->user_model->checkUser(array('username'=>$_GET['username']));
            unset($_GET['username']);
        }
        if(isset($_GET['phone'])){
            $user=$this->user_model->checkUser(array('phone'=>$_GET['phone']));
            unset($_GET['phone']);
        }
        $data=$_GET;
        if($user){
            $data['user_id']=$user['id'];
        }
        $start = $data['iDisplayStart']; //显示的起始索引
        $length = $data['iDisplayLength'];//显示的行数
        $sort_th = $data['mDataProp_'.$data['iSortCol_0'].''];//被排序的列
        $sort_type = $data['sSortDir_0'];//排序的方向 "desc" 或者 "asc".
        $search = $data ['sSearch'];//全局搜索字段
       
        $where=' 1=1 ';
        if(isset($data['user_id'])){
            $where.=' and user_id='.$data['user_id'];
        }
		
        if($this->admin['admin_type']=='user' ){
            $where.=' and user_id='.$this->admin['id'];
        }
		
		$userid_where = '';
        if($this->admin['admin_type']=='admin'){
        	$userid_where='';
        	if(isset($data['username']) && $data ['username']){
        		$sql = "SELECT id FROM user WHERE locate ('".$data['username']."' , user.username) > 0";
        		$query = $this->db->query($sql);
        		$user_ids=array();
        		foreach ($query->result() as $row){
        			$user_ids[]= $row->id;
        		}
        		$userid_where="  user_id in(".implode(',',$user_ids).")";
        		unset($data['username']);
        	}
        }
        $data_where='';
        if(isset($data['start_time']) && $data['start_time']){
        	$data_where='cash.create_time >='.strtotime($data['start_time']);
        	unset($data['start_time']);
        }
    	if(isset($data['end_time']) && $data['end_time']){
        	$data_where.=' and cash.create_time <='.strtotime($data['end_time']);
        	unset($data['end_time']);
        }
        if($data_where && $userid_where){
        	$where.='and ('.$userid_where.' '.$data['select_type'].' '.$data_where.')';
        }else if($data_where){
        	$where.=' and '.$data_where;
        }else if($userid_where){
        	$where.=' and '.$userid_where;
        }
        $this->data['count'] = $this->cash_model->getCount($where);
		
        $aaData=array();
        if($this->data['count']){
            $order_by = $sort_th." ".$sort_type;
            $cash_list = $this->cash_model->getCashList($where,$length,$start,$order_by);
            
            $result=array();
            $users=array();
            $is_shenhe=$this->Isallow('cash', 'shenhe_page');
            foreach($cash_list as $key=>$value){
                $shenhe_url='';
                switch ($value['status']){
                    case '0': 
                        $value['status_text']='已提交';
                        
                        if($is_shenhe){
                            $shenhe_url = '<a href="/admin/cash/shenhe_page/?id='.$value['id'].'"><span class="btn btn-xs btn-success cancel">审核</span></a>';
                        }
                        break;
                    case '1': 
                        $value['status_text']='已拒绝';
                        break;
                    case '2': 
                        $value['status_text']='已完成';
                        break;
                    case '3': 
                        $value['status_text']='已取消';
                        break;
                }
                if(isset($users[$value['user_id']])){
                    $value['true_name']=$users[$value['user_id']]['true_name'];
                }
                $value['create_time']=date('Y-m-d H:i:s',$value['create_time']);
                $value['last_time']=date('Y-m-d H:i:s',$value['last_time']);
//                 $user_info=$this->user_model->checkUser(array('id'=>$value['user_id']),'true_name,tixian');
//                 if($user_info){
//                     $value['true_name']=$user_info['true_name'];
//                     $users[$value['user_id']]['true_name']=$user_info['true_name'];
//                 }
                
               $value['check'] = '<label><input name="c_id" type="checkbox" value="'.$value['id'].'" /></label>';
               
                $value['operate']=$shenhe_url;
                $result[]=$value;
            }
            $aaData=$result;
            
        }
        $output['aaData'] = $aaData;
        $output['sEcho'] = $_GET['sEcho'];
        $output['iTotalDisplayRecords'] =  $this->data['count']; //总共有几条数据
        $output['iTotalRecords'] = $this->data['count']; //总共有几条数据
        echo json_encode($output); //最后把数据以json格式返回
    }
    /**
     *提现
     */
    public function add_page(){
        if(isset($_GET['user_id'])){
            $this->load->model('user_model');
            $user=$this->user_model->checkUser(array('id'=>$_GET['user_id'],'id,username,true_name,balance,tixian,bank_account,bank_name'));
            $is_ok=false;
            if($this->admin['admin_type']== 'admin' ||( $user['bank_name'] && $user['bank_account'])){
                $is_ok=true;
            }
            $this->data['is_ok']=$is_ok;
            $this->data['true_name']=$user['true_name'];
            $this->data['username']=$user['username'];
            $this->data['balance']=$user['balance'];
            $this->data['user_id']=$user['id'];
            $this->data['kebalance']=$user['balance']-($user['balance']*0.1);
            $this->data['tixian']=$user['tixian'];
            $this->data['is_admin']=$this->admin['admin_type'];
            $this->load->view('/admin/cash_add.php',  $this->data);
        }else{
            $this->location_href("/admin/user/user_list/6?parent_id=".$_GET['user_id']);
        }
    }
    /**
     * 添加申请提现记录
     */
    public function add(){
        $message=false;
		$is_success=true;
        if($this->admin['admin_type']=='user'){
            if(empty($_POST['username']) || empty($_POST['password'])){
				$message='参数不完整';
				 $is_success=false;
			}
        }
	   if($is_success){
            $this->load->model('user_model');
            $user=$this->user_model->checkUser(array('username'=>$_POST['username']),'id,username,password2,true_name,money,freeze,balance,tixian,tax,feiyong,bank_name,bank_account');
            if(empty($user)){
                $message='用户不存在';
				$is_success=false;
            }else{
               
                if($this->admin['admin_type']=='user'){
                   if($user['password2']!=md5($_POST['password'])){
                        $message='交易密码错误';
                        $is_success=false;
                   }else if(!$user['bank_name'] || !$user['bank_account']){
                       $message='请在会员列表编辑银行信息';
                       $is_success=false;
                   }
				   if(($user['balance']-$_POST['money'])<0){
					   $message='余额不足';
                       $is_success=false;
				   }
                }
                if( $is_success ){
                    $tax=$_POST['money']*0.08;
                    $feiyong=$_POST['money']*0.02;
                    $shiji_money=$_POST['money']-($tax+$feiyong);
                    $data['user_id']=$user['id'];
                    $data['money']  =$_POST['money'];
                    $data['bank_name']  =$user['bank_name'];
                    $data['bank_account']  =$user['bank_account'];
                    $data['freeze']  =$_POST['money'];
                    $data['status'] =0;
                    $data['create_time']=time();
                    $data['last_time']  =time();
                    $data['operation']  =$this->admin['username'];
                    
                    $data['balance']    =$user['balance']-$_POST['money'];
                    $data['shiji_money']=$shiji_money;
                    $data['tax']=$tax;
                    $data['feiyong']=$feiyong;
                    $result=$this->cash_model->add($data);
                    if($result){
                        $update_data['balance']=$data['balance'];
                        $update_data['freeze']=$user['freeze']+$_POST['money'];
                        $update_data['tixian']=$user['tixian']+$_POST['money'];
                        $update_data['tax']=$user['tax']+$tax;
                        $update_data['feiyong']=$user['feiyong']+$feiyong;
                        $update=$this->user_model->editUser(array('id'=>$user['id']),$update_data);
                        $update=true;
                        if($update){
                            $logdata[]=array(
                                'user_id'=>$user['id'],
                                'username'=>$user['username'],
                                'true_name'=>$user['true_name'],
                                'money'=>'-'.$shiji_money,
                                'type' =>'tixian',
                                'remark'=>$user['true_name'].'您于'.date('Y-m-d H:i:s',time())."申请提现".$_POST['money']."元，扣除税费手续费".($feiyong+$tax)."实际到账".$shiji_money.'元',
                                'create_time'=>  time()
                            );
                            
                            $logdata[]=array(
                                'user_id'=>$user['id'],
                                'username'=>$user['username'],
                                'true_name'=>$user['true_name'],
                                'money'=>'-'.($feiyong+$tax),
                                'type' =>'feiyong',
                                'remark'=>$user['true_name'].'您本次提现产生了'.($feiyong+$tax).'费用已冻结',
                                'create_time'=>  time()
                            );
                            $this->add_money_log($logdata);
                            $this->location_href($this->go_url."/4");exit;
                        }else{
                            $this->cash_model->deleteCash(array('id'=>$result));
                            $message='添加失败';
                        }
                    }
                }
            }
        }
        $this->location_href($this->go_url."/5?message=".$message);
    }
    /**
     * 税收8%
     */
    public function tax(){
        
    }
    /**
     * 管理费
     */
    public function feiyong(){
        
    }
    /**
     * 验证二级密码
     */
    public function check_password(){
        $message=false;
        if(empty($_POST['username']) || empty($_POST['password'])){
            $message=false;
            
        }else{
            $this->load->model('user_model');
            $user=$this->user_model->checkUser(array('username'=>$_POST['username']),'username,password2');
            if(empty($user)){
                $message=false;
            }else{
                if($user['password2']==md5($_POST['password'])){
                    $message=true;
                }
            }
        }
        echo json_encode($message);
    }
    
    /**
     * 审核提现
     */
    public function shenhe_page(){
        $id=array();
        if(isset($_GET['id'])){
            $id[]=$_GET['id'];
        }else{
            $id=explode(',',$_POST['str']);
            
        }
        if($id){
            $cash_list=$this->cash_model->select('cash.*,user.username,user.true_name,user.id as user_id ,user.money as user_money,user.system_money,user.tixian')
		->join('user','user.id = cash.user_id')->where_in('cash.id',$id)->find_all();
            $this->data['cash_list']=$cash_list;
            $this->load->view('/admin/cash_shenhe_page.php',$this->data);
        }
    }
    /**
     * 审核
     */
    public function shenhe(){
        $type='url';
        if(isset($_POST['str'])){
            $id=explode(',',$_POST['str']);
            $_POST['statsus']='1';
            $_POST['remark']=$this->admin['username'].'批量审核';
            $type='json';
        }else{
            $id=$_POST['id'];
        }
        $data['status']=$_POST['status'];
        $data['remark']=$_POST['remark'];
        $result=$this->cash_model->where_in('id',$id)->edit($data);
        if($result){
            
            $message=true;
            if($type=='json'){
                echo json_encode($message);
            }else{
                $this->location_href($this->go_url."/2");
            }
        }else{
            $message=false;
            if($type=='json'){
                echo json_encode($message);
            }else{
                $this->location_href($this->go_url."/3");
            }
        }
    }
    
}
